//
// Copyright 2022 The Sparrow Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#ifndef SPARROW_IMPL_TIME_H_
#define SPARROW_IMPL_TIME_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>

#include "sparrow/impl/export.h"

struct sp_time_sepc_t {
    int64_t tv_sec;
    int64_t tv_nsec;
};

SPARROW_API void sp_time_init();
SPARROW_API void sp_system_clock(struct sp_time_sepc_t *ts);
SPARROW_API void sp_steady_clock(struct sp_time_sepc_t *ts);

#define SP_TIMESPEC_MILLI(ts) (int64_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000)
#define SP_TIMESPEC_MICRO(ts) (int64_t)(ts.tv_sec * 1000000 + ts.tv_nsec / 1000)
#define SP_TIMESPEC_NANOS(ts) (int64_t)(ts.tv_sec * 1000000000 + ts.tv_nsec)

//
/**
 * @brief Copies into ptr the content of format, expanding its format specifiers into the
 * corresponding values that represent the time described in timeptr, with a limit of maxsize
 * characters.
 *
 * @param fmt C string containing any combination of regular characters and special format
 * specifiers
 * @param buff Pointer to the destination array where the resulting C string is copied
 * @return the total number of characters copied to buff (not including the
 * terminating null-character). Otherwise, it returns zero, and the contents
 * of the array pointed by ptr are indeterminate.
 *
 * @note just like function 'strftime'
 * @example
 * char buff[32] = {0};
 * int len = sp_format_time("%F %T", buff);
 * "%F %T" -> 2020-05-10 01:43:06
 */
SPARROW_API int sp_format_time(const char *fmt, char buff[32]);

#ifdef __cplusplus
} /* end extern "C" */
#endif
#endif // SPARROW_IMPL_TIME_H_
